package com.gydz.interferencenetworkmanagement.common.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;

import java.nio.charset.Charset;
import java.util.Date;

/*
* 配置服务处理器类
* */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println(new Date() + ": 客户端写出数据");

        // 1.连接成功后设置数据
        String str = "hello";
        ByteBuf buffer = getByteBuf(ctx,str);
        // 2.发送数据
        ctx.channel().writeAndFlush(buffer);
    }

    private ByteBuf getByteBuf(ChannelHandlerContext ctx,String str) {
        byte[] bytes = str.getBytes(Charset.forName("utf-8"));
        ByteBuf buffer = ctx.alloc().buffer();
        buffer.writeBytes(bytes);
        return buffer;
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object object) {
        ByteBuf byteBuf = null;
        if(DatagramPacket.class.equals(object.getClass())) {    //udp传输接收
            DatagramPacket pa = (DatagramPacket)object;
            byteBuf = pa.content();
            System.out.println(new Date() + ": 客户端读到数据 -> " + byteBuf.toString(Charset.forName("utf-8")));
        }else {
            byteBuf = (ByteBuf) object;

            System.out.println(new Date() + ": 客户端读到数据 -> " + byteBuf.toString(Charset.forName("utf-8")));
        }



    }
}
